package com.cg.controller.user;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.poi.hpsf.SummaryInformation;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.CellRangeAddress;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cg.controller.AbstractController;
import com.cg.entity.SysUserEntity;
import com.cg.entity.UserInfo;
import com.cg.service.impl.UserInfoService;
import com.cg.utils.Constant;
import com.cg.utils.DateUtils;
import com.cg.utils.Query;
import com.cg.utils.R;
import com.cg.utils.UploadUtil;
import com.cg.utils.annotation.SysLog;



@RestController
@RequestMapping("/sys/baseuser")
public class BaseUserController{
	
	
	@Autowired
	UserInfoService userInfoService;
	
	@Autowired
	private UploadUtil uploadUtil;
	/**访问地址*/
	@Value("${global.upload.path}")
	private String path;
	/**存放地址*/
	@Value("${global.upload.docBase}")
	private String docBase;
	
	private String mypath="headpic/";
	/**
	 * 所有列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:baseuser:list")
	public R list(@RequestParam Map<String, Object> params){
		//只有超级管理员，才能查看所有管理员列表
//		if(getUserId() != Constant.SUPER_ADMIN){
//			params.put("createUserId", getUserId());
//		}
		
		//查询列表数据
		Query query = new Query(params);
//		
//		userinfo baseuser=new userinfo();
		List<UserInfo> userinfoList = userInfoService.queryList(query);
		int total = userInfoService.queryTotal(query);
		
		//PageUtils pageUtil = new PageUtils(userList, total, query.getLimit(), query.getPage());
		
		return R.success(total, "", userinfoList);
	}
	
	/**
	 * 获取评论信息
	 */
	@RequestMapping("/info")
	public R info(){
		return R.ok().put("userinfo", null);
	}
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{id}")
	@RequiresPermissions("sys:baseuser:info")
	public R info(@PathVariable("id") Long id){
		UserInfo userinfo = userInfoService.queryObject(id);
		
		
		return R.ok().put("userinfo", userinfo);
	}
	
	/**
	 * 用户列表
	 */
	@RequestMapping("/select")
	@RequiresPermissions("sys:baseuser:select")
	public R select(){
		Map<String, Object> map = new HashMap<>();
		
		List<UserInfo> list = userInfoService.queryList(map);
		
		return R.ok().put("list", list);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("")
	@RequestMapping("/save")
	@RequiresPermissions("sys:baseuser:save")
	public R save(@RequestBody UserInfo user){
		
		user.setCreateTime(DateUtils.dateToDateString(new Date()));
		userInfoService.save(user);
		
		return R.ok();
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("")
	@RequestMapping("/save2")
	@RequiresPermissions("sys:baseuser:save")
	public R save2(HttpServletRequest request,UserInfo user){
		
		user.setCreateTime(DateUtils.dateToDateString(new Date()));
		String filePath = uploadUtil.uploadImg(request,mypath);
		user.setHeadPic(filePath);
		user.setPasswrod("123456");
		userInfoService.save(user);
		return R.ok();
		
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("")
	@RequestMapping("/upload")
	@RequiresPermissions("sys:baseuser:save")
	public R upload(HttpServletRequest request,UserInfo user){
		
		user.setCreateTime(DateUtils.dateToDateString(new Date()));
//		String filePath = uploadUtil.uploadImg(request,mypath);
		
		try {
//            String path = request.getSession().getAttribute("url").toString();
			// 转型为MultipartHttpRequest：   
	        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
	        // 获得文件：   
	        MultipartFile file = multipartRequest.getFile("file");   
//	        CommonsMultipartFile cf= (CommonsMultipartFile)file; 
//	        DiskFileItem fi = (DiskFileItem)cf.getFileItem(); 
//            File f = fi.getStoreLocation();
//            FileInputStream fis = new FileInputStream((File)file);
            Workbook book = new XSSFWorkbook(file.getInputStream());
            importData(book);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
		
//		user.setPasswrod("123456");
//		userInfoService.save(user);
		return R.ok();
		
	}
	 public void importData(Workbook workBook) {
		 	Sheet  sheet = workBook.getSheetAt(0);
	        int startReadRow = 3;
	        int lastRowNum = sheet.getLastRowNum();
	        for(int i = startReadRow; i <= lastRowNum; i++) {
	            try {
	            	UserInfo entity = new UserInfo();

	            	Row  row = sheet.getRow(i);
	            	for(int j=0;j<row.getLastCellNum();j++) {
	            		Cell cell = row.getCell(j); 
		            	if(cell!=null) {
		            		 //用户编号
			                String id = String.valueOf(cell.getStringCellValue());
//			                entity.setId(id);
			                System.out.println("idididid=="+id);
			                //用户姓名
			                String userName = cell.getStringCellValue();
			                entity.setUserName(userName);
			                System.out.println("userNameuserName=="+userName);
		            	}
	            		
	            	}
	            	
	               
	                //年龄
//	                int age = Integer.valueOf(row.getCell(2).getStringCellValue());
//	                entity.setAge(age);
	                
//	                userMapper.addUser(entity);
	            } catch (Exception e) {
	                e.printStackTrace();
//	                return new ExtJsObject(true, "导入失败", null);
	            }
	        }
//	        return null;
	    }

	
		
	/** 总行数 */
    private int totalRows = 0;
    /** 总列数 */
    private int totalCells = 0;
    /** 错误信息 */
    private String errorInfo;
    
    public int getTotalCells() {
        return totalCells;
    }
    
    public List<List<String>> read(HttpServletResponse response) {
        List<List<String>> dataLst = new ArrayList<List<String>>();
        OutputStream is = null;
        try {
        	is = response.getOutputStream();
        	
        	 /** 判断文件的类型，是2003还是2007 */
            boolean isExcel2003 = true;
//            if (WDWUtil.isExcel2007(filePath)) {
//                isExcel2003 = false;
//            }
            
            dataLst = read(is, false);
            is.close();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    is = null;
                    e.printStackTrace();
                }
            }
        }
        /** 返回最后读取的结果 */
        return dataLst;
    }
    
    
	private List<List<String>> read(OutputStream is,boolean flag) {
		
		Workbook  wb = new HSSFWorkbook();
        List<List<String>> dataLst = new ArrayList<List<String>>();
        /** 得到第一个shell */
        Sheet sheet = wb.getSheetAt(0);
        /** 得到Excel的行数 */
        this.totalRows = sheet.getPhysicalNumberOfRows();
        /** 得到Excel的列数 */
        if (this.totalRows >= 1 && sheet.getRow(0) != null) {
            this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
        }
        /** 循环Excel的行 */
        for (int r = 0; r < this.totalRows; r++) {
            Row row = sheet.getRow(r);
            if (row == null) {
                continue;
            }
            List<String> rowLst = new ArrayList<String>();
            /** 循环Excel的列 */
            for (int c = 0; c < this.getTotalCells(); c++) {
                Cell cell = row.getCell(c);
                String cellValue = "";
                if (null != cell) {
                    // 以下是判断数据的类型
                    switch (cell.getCellType()) {
                    case HSSFCell.CELL_TYPE_NUMERIC: // 数字
                        cellValue = cell.getNumericCellValue() + "";
                        break;
                    case HSSFCell.CELL_TYPE_STRING: // 字符串
                        cellValue = cell.getStringCellValue();
                        break;
                    case HSSFCell.CELL_TYPE_BOOLEAN: // Boolean
                        cellValue = cell.getBooleanCellValue() + "";
                        break;
                    case HSSFCell.CELL_TYPE_FORMULA: // 公式
                        cellValue = cell.getCellFormula() + "";
                        break;
                    case HSSFCell.CELL_TYPE_BLANK: // 空值
                        cellValue = "";
                        break;
                    case HSSFCell.CELL_TYPE_ERROR: // 故障
                        cellValue = "非法字符";
                        break;
                    default:
                        cellValue = "未知类型";
                        break;
                    }
                }
                rowLst.add(cellValue);
            }
            /** 保存第r行的第c列 */
            dataLst.add(rowLst);
        }
        return dataLst;
    }
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("sys:baseuser:update")
	public R update(@RequestBody UserInfo userinfo){
		
//		baseuser.set(getUserId());
		userInfoService.update(userinfo);
		
		return R.ok();
	}
	
	/**
	 * 上传
	 */
	@SysLog("上传")
	@RequestMapping("/update2")
	@RequiresPermissions("sys:baseuser:update")
	public R upload(HttpServletRequest request,UserInfo userinfo,String gridId){
		
//		HttpServletRequest req = XssHttpServletRequestWrapper.getOrgRequest(request);
//		List<String> filePath = uploadUtil.upload(req,docBase, path,"resource/appmenu/");
//		 UserInfo userinfo=new UserInfo();
		String filePath = uploadUtil.uploadImg(request,mypath);
		userinfo.setHeadPic(filePath);
		userInfoService.update(userinfo);
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除评论")
	@RequestMapping("/delete")
	@RequiresPermissions("sys:baseuser:delete")
	public R delete(@RequestBody Long[] ids){
		
		userInfoService.deleteBatch(ids);
		
		return R.ok();
	}
	
	/**
	 * 导出
	 */
	@SysLog("删除评论")
	@RequestMapping("/export")
	@RequiresPermissions("sys:baseuser:delete")
	public R export(){
		Map<String, String> headMap = new HashMap<>();
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		exportExcel("excel",headMap,new JSONArray(),"123",123,os);
		
		return R.ok();
	}
	public static String NO_DEFINE = "no_define";//未定义的字段
    public static String DEFAULT_DATE_PATTERN="yyyy年MM月dd日";//默认日期格式
    public static int DEFAULT_COLOUMN_WIDTH = 17;
	 /**
     * 导出Excel 97(.xls)格式 ，少量数据
     * @param title 标题行 
     * @param headMap 属性-列名
     * @param jsonArray 数据集
     * @param datePattern 日期格式，null则用默认日期格式
     * @param colWidth 列宽 默认 至少17个字节
     * @param out 输出流
     */
    public static void exportExcel(String title,Map<String, String> headMap,JSONArray jsonArray,String datePattern,int colWidth, OutputStream out) {
        if(datePattern==null) datePattern = DEFAULT_DATE_PATTERN;
        // 声明一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        workbook.createInformationProperties();
        workbook.getDocumentSummaryInformation().setCompany("*****公司");
        SummaryInformation si = workbook.getSummaryInformation();
        si.setAuthor("JACK");  //填加xls文件作者信息
        si.setApplicationName("导出程序"); //填加xls文件创建程序信息
        si.setLastAuthor("最后保存者信息"); //填加xls文件最后保存者信息
        si.setComments("JACK is a programmer!"); //填加xls文件作者信息
        si.setTitle("POI导出Excel"); //填加xls文件标题信息
        si.setSubject("POI导出Excel");//填加文件主题信息
        si.setCreateDateTime(new Date());
         //表头样式
        HSSFCellStyle titleStyle = workbook.createCellStyle();
        titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont titleFont = workbook.createFont();
        titleFont.setFontHeightInPoints((short) 20);
        titleFont.setBoldweight((short) 700);
        titleStyle.setFont(titleFont);
        // 列头样式
        HSSFCellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        HSSFFont headerFont = workbook.createFont();
        headerFont.setFontHeightInPoints((short) 12);
        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        headerStyle.setFont(headerFont);
        // 单元格样式
        HSSFCellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        HSSFFont cellFont = workbook.createFont();
        cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        cellStyle.setFont(cellFont);
        // 生成一个(带标题)表格
        HSSFSheet sheet = workbook.createSheet();
        // 声明一个画图的顶级管理器
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
        // 定义注释的大小和位置,详见文档
        HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
                0, 0, 0, (short) 4, 2, (short) 6, 5));
        // 设置注释内容
        comment.setString(new HSSFRichTextString("可以在POI中添加注释！"));
        // 设置注释作者，当鼠标移动到单元格上是可以在状态栏中看到该内容.
        comment.setAuthor("JACK");
        //设置列宽
        int minBytes = colWidth<DEFAULT_COLOUMN_WIDTH?DEFAULT_COLOUMN_WIDTH:colWidth;//至少字节数
        int[] arrColWidth = new int[headMap.size()];
        // 产生表格标题行,以及设置列宽
        String[] properties = new String[headMap.size()];
        String[] headers = new String[headMap.size()];
        int ii = 0;
        for (Iterator<String> iter = headMap.keySet().iterator(); iter
                .hasNext();) {
            String fieldName = iter.next();

            properties[ii] = fieldName;
            headers[ii] = fieldName;

            int bytes = fieldName.getBytes().length;
            arrColWidth[ii] =  bytes < minBytes ? minBytes : bytes;
            sheet.setColumnWidth(ii,arrColWidth[ii]*256);
            ii++;
        }
        // 遍历集合数据，产生数据行
        int rowIndex = 0;
        for (Object obj : jsonArray) {
            if(rowIndex == 65535 || rowIndex == 0){
                if ( rowIndex != 0 ) sheet = workbook.createSheet();//如果数据超过了，则在第二页显示

                HSSFRow titleRow = sheet.createRow(0);//表头 rowIndex=0
                titleRow.createCell(0).setCellValue(title);
                titleRow.getCell(0).setCellStyle(titleStyle);
                sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headMap.size() - 1));

                HSSFRow headerRow = sheet.createRow(1); //列头 rowIndex =1
                for(int i=0;i<headers.length;i++)
                {
                    headerRow.createCell(i).setCellValue(headers[i]);
                    headerRow.getCell(i).setCellStyle(headerStyle);

                }
                rowIndex = 2;//数据内容从 rowIndex=2开始
            }
            JSONObject jo = (JSONObject) JSONObject.toJSON(obj);
            HSSFRow dataRow = sheet.createRow(rowIndex);
            for (int i = 0; i < properties.length; i++)
            {
                HSSFCell newCell = dataRow.createCell(i);

                Object o =  jo.get(properties[i]);
                String cellValue = ""; 
                if(o==null) cellValue = "";
                else if(o instanceof Date) cellValue = new SimpleDateFormat(datePattern).format(o);
                else cellValue = o.toString();

                newCell.setCellValue(cellValue);
                newCell.setCellStyle(cellStyle);
            }
            rowIndex++;
        }
        // 自动调整宽度
        /*for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }*/
        try {
            workbook.write(out);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
